package com.bmsoft.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.bmsoft.dto.Response;
import com.bmsoft.dto.StaffDto;
import com.bmsoft.dto.ResponseDTO;
import com.bmsoft.service.LoginService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录注册接口
 *
 * @Author : qiujie
 * @Date : 2022/1/30
 */
@RestController
public class LoginController {

    @Resource
    private LoginService loginService;

    private final static String SESSION_KEY = "captcha";    // 验证码session key

    @PostMapping("/login")
    public ResponseDTO login(@RequestBody StaffDto staff, HttpServletRequest request) throws Exception {
        String captcha = request.getHeader(SESSION_KEY);//获取请求头中正确的验证码
        String code = staff.getYzmcode();//用户输入的验证码
        if(code.isEmpty()){
            return  Response.error("请输入验证码！");
        }
        //不区分大小写进行校验
        if (!code.equalsIgnoreCase(captcha)) {
            return  Response.error("验证码错误！");
        }
        return this.loginService.login(staff);
    }



    //获取图形验证码
    @GetMapping("/captcha")
    public void generateCaptcha(HttpServletResponse response) throws Exception {
        // 创建一个线型验证码实例
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(100, 36, 4,40); // 宽度、高度、字符和干扰线数量可自定义

        // 设置验证码内容和输出到http响应
        String code = captcha.getCode(); // 获取验证码文本内容
        captcha.write(response.getOutputStream()); // 输出图片到浏览器

        //将验证码内容存入响应头中
        response.setHeader(SESSION_KEY, code);//这里的SESSION_KEY是我在前面自定义的一个常量字符串

    }
}
